//
//  EssenceViewController.m
//  Otaku
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "EssenceViewController.h"
#import "LWXCycleView.h"
#import "EssenceModel.h"
#import "EssenceCell.h"

@interface EssenceViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *essenceTableView;

@property (nonatomic, strong) NSMutableArray *cycleArray;

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) LWXCycleView *cycleView;

@property (nonatomic, strong) NSString *currentSkinModel;


//请求内容起始条数
@property (nonatomic, strong) NSString *start;


@end

@implementation EssenceViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkinModel) name:SkinModelDidChangedNotification object:nil];
    [self updateSkinModel];
    
}


- (void)updateSkinModel {
    
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] stringForKey:CurrentSkinModelKey];
    
    if ([self.currentSkinModel isEqualToString:NightSkinModelValue]) {
        self.view.backgroundColor = [UIColor blackColor];
//        self.nameTextField.backgroundColor = [UIColor darkGrayColor];
//        self.SignatureTextView.backgroundColor = [UIColor darkGrayColor];
//        self.nameTextField.textColor  = [UIColor grayColor];
//        self.SignatureTextView.textColor = [UIColor grayColor];
        
    }else {
        self.view.backgroundColor = [UIColor colorWithRed:250.0/255.0 green:250.0/255.0  blue:250.0/255.0  alpha:1.0];
//        self.nameTextField.backgroundColor = [UIColor whiteColor];
//        self.SignatureTextView.backgroundColor = [UIColor whiteColor];
//        self.nameTextField.textColor = [UIColor blackColor];
//        self.SignatureTextView.textColor = [UIColor blackColor];
        
    }
    
}

- (UITableView *)essenceTableView {
    if (!_essenceTableView) {
        _essenceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, FUll_VIEW_WIDTH, FUll_CONTENT_HEIGHT - PageBtn) style:UITableViewStylePlain];
    }
    return _essenceTableView;
}


- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray new];
    }
    return _dataArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.essenceTableView.delegate = self;
    self.essenceTableView.dataSource = self;
    
    self.cycleView = [[LWXCycleView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 250) interVal:3];
    self.cycleView.imgNameArray = [@[@"1",@"2",@"3"] mutableCopy];
    
    [self loadDataFromServerType:self.type Start:self.start];
    self.essenceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.essenceTableView addSubview:self.cycleView];
    [self.view addSubview:self.essenceTableView];
    
    //注册cell
    [self.essenceTableView registerNib:[UINib nibWithNibName:@"EssenceCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    
    //添加上提加载更多
    __weak typeof(self) weakSelf = self;
    [self.essenceTableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.dataArray.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf loadDataFromServerType:nil Start:weakSelf.start];
    }];
}



//数据解析
-(void)loadDataFromServerType:(NSString *)type Start:(NSString *)start {
    [LWXNetWorkRequestManager requestURL:[NSURL URLWithString:@"http://toutiao.com/ma/"] Method:LWX_GET Params:@{@"media_id":@5234320301,@"count":@10,@"max_behot_time":@0,@"callback":@"jsonp1",@"csrfmiddlewaretoken":@"undefined",@"_":@1462282384023} Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *string = [self responseStringWithString:[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]];
        NSData *cnData = [string dataUsingEncoding:NSUTF8StringEncoding];
        if (cnData) {
             NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:cnData options:NSJSONReadingMutableContainers error:nil];
            NSMutableArray *array = jsonDict[@"data"];
            for (NSDictionary *dict in array) {
                EssenceModel *model = [EssenceModel new];
                [model setValuesForKeysWithDictionary:dict];
                [self.dataArray addObject:model];
              
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.essenceTableView reloadData];
                [[self.essenceTableView defaultFooter]endRefreshing];
            });
            
        }
        
    }];
}


//将返回结果转成string
- (NSString *)responseStringWithString:(NSString *)dataString
{
    NSString *jsonString;
    NSRange jsonStart = [dataString rangeOfString:@"("];
    jsonStart.location++;
    
    NSRange jsonEnd = [dataString rangeOfString:@")" options:NSBackwardsSearch];
    jsonEnd.location--;
    
    if (jsonStart.length > 0 && jsonEnd.length > 0) {
        NSRange range = NSUnionRange(jsonStart, jsonEnd);
        jsonString = [dataString substringWithRange:range];
    }
    return jsonString;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return self.dataArray.count;
  
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        return cell;
    }else {
        
        EssenceCell *Essecell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
        if ([self.currentSkinModel isEqualToString:DaySkinModelValue]) {//日间模式
            [Essecell updateToDaySkinMode];
        } else {
            [Essecell updateToNightSkinMode];
        }
        Essecell.model = self.dataArray[indexPath.row];
        return Essecell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        return 280;
    }else if (indexPath.row > 0){
        return 80;
    }
    return 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
